import request from "../utils/request";

export interface TaskRequest {
  taskType?: string;
  status?: number;
  priority?: number;
  page?: number;
  size?: number;
  keyword?: string;
}

export interface TaskStats {
  total: number;
  pending: number;
  processing: number;
  completed: number;
  overdue: number;
  highPriority: number;
}

export interface Task {
  id: number;
  userId: number;
  taskType: string;
  title: string;
  description: string;
  sourceId?: number;
  sourceType?: string;
  priority: number;
  status: number;
  dueTime?: string;
  completionTime?: string;
  reminderCount: number;
  autoGenerated: boolean;
  createTime: string;
  updateTime: string;
}

// 构建查询参数字符串
const buildQueryParams = (params: Record<string, any>): string => {
  const searchParams = new URLSearchParams();
  Object.entries(params).forEach(([key, value]) => {
    if (value !== undefined && value !== null && value !== "") {
      searchParams.append(key, String(value));
    }
  });
  const queryString = searchParams.toString();
  return queryString ? `?${queryString}` : "";
};

export const taskApi = {
  // 获取任务列表
  getTasks: (params: TaskRequest) => {
    const queryParams = buildQueryParams(params);
    return request.get(`/api/v1/task/list${queryParams}`);
  },

  // 获取任务统计信息
  getStats: () => {
    return request.get("/api/v1/task/stats");
  },

  // 获取即将到期的任务
  getUpcomingTasks: (days: number = 7) => {
    return request.get(`/api/v1/task/upcoming?days=${days}`);
  },

  // 创建任务
  createTask: (task: Partial<Task>) => {
    return request.post("/api/v1/task/create", task);
  },

  // 更新任务
  updateTask: (id: number, task: Partial<Task>) => {
    return request.put(`/api/v1/task/${id}`, task);
  },

  // 删除任务
  deleteTask: (id: number) => {
    return request.delete(`/api/v1/task/${id}`);
  },

  // 完成任务
  completeTask: (id: number) => {
    return request.post(`/api/v1/task/${id}/complete`);
  },

  // 批量操作任务
  batchOperation: (operation: string, ids: number[]) => {
    return request.post("/api/v1/task/batch", { operation, ids });
  },

  // 设置任务提醒
  setReminder: (id: number, reminderTime: string) => {
    return request.post(`/api/v1/task/${id}/reminder`, { reminderTime });
  },

  // 获取任务详情
  getTask: (id: number) => {
    return request.get(`/api/v1/task/${id}`);
  },

  // 获取今日任务
  getTodayTasks: () => {
    return request.get("/api/v1/task/today");
  },

  // 获取本周任务
  getWeekTasks: () => {
    return request.get("/api/v1/task/week");
  },
};
